<?php
defined('SYSPATH') or die('No direct script access.');

class Controller_Notes extends Controller_Initialize {

  public $secure_actions = array(
      // user actions
      'index' => 'login',
      'view' => 'login',
      'read' => 'login',
      'delete' => 'login',
  );

  public function before() {
    // Execute parent::before first
    parent::before();

  }

  public function action_index() {

    $view = View::factory('templates/notes/new');

    if (!empty($_POST)) {

      $notes_user = null;
      $notes_user = ORM::factory('notes_user');
      $post = $notes_user->validate_add_note($_POST);

      if ($post->check()) {
        echo Kohana::debug($post);
        $notes_user->username = $this->userAuth->username;
        $notes_user->text = $post['text'];
        $notes_user->date = strtotime($post['date']);
        $notes_user->save();
        if ($notes_user->saved()) {
          Message::add('success', 'Poznámka byla uložena.');
          Request::instance()->redirect('notes');
        }
      } else {
        $view->set('dataPost', $_POST);
        Message::add('warning', '<strong>Poznámka nebyla uložena.</strong> ');
      }
    }

    $this->template->content = $view;
    
  }

  public function action_view() {

    $this->template->content = View::factory('templates/notes/view')
                    ->bind('notes_user', $notes_user);

    $notes_user = ORM::factory('notes_user')->where('username', '=', $this->userAuth->username)->find_all();

  }

  public function action_read($id) {

    $this->template->content = View::factory('templates/notes/read')
      ->bind('notes_user', $notes_user);

    $notes_user = ORM::factory('notes_user')->where('username', '=', $this->userAuth->username)->find($id);
  }

  public function action_delete($id) {
    
      if (ORM::factory('notes_user')->where('username', '=', $this->userAuth->username)->delete($id)) {
        Message::add('success', 'Poznámka byla smazána.');
      }

    Request::instance()->redirect('notes/view');

  }

  public function after() {
    if ($this->auto_render === TRUE) {

      $scripts = array('media/js/jquery-ui-timepicker-addon.js');

      $this->template->scripts = array_reverse(array_merge($this->template->scripts, $scripts));
    }

    // Run anything that needs to run after this.
    parent::after();
  }

}